package com.shaw.workrecord.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.shaw.workrecord.consts.Consts;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;

public class JWTUtils {
    //秘钥加密解密都需要，所以定义成静态常量
    public static final String SIGNATURE = "andrew";

    public static String createToken(HashMap<String,String> hashMap) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);
        JWTCreator.Builder builder = JWT.create();
        //遍历map集合,将信息放到payload的Claim中
//        hashMap.forEach(builder::withClaim);
        String token = builder.withExpiresAt(instance.getTime())
                .withSubject("subject")
                .withClaim("id", Integer.valueOf(hashMap.get("id")))
                .sign(Algorithm.HMAC256(SIGNATURE)); //加密

        return token;
    }

    /**
     * 验证token  DecodedJWT 为解密之后的对象 可以获取payload中添加的数据
     * @param token
     * @return
     */
    public static DecodedJWT verifyToken(String token){
        //进行token的校验,注意使用同样的算法和同样的秘钥
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    /**
     * 不验证token是否过期，获取token信息
     * @param token
     * @return
     */
    public static DecodedJWT decodeToken(String token){
        return JWT.decode(token);
    }

    public static Long getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("id").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static Long getUserId() {
        try {
            DecodedJWT jwt = JWT.decode(getToken());
            return jwt.getClaim("id").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获取当前请求对象
     * @return
     */
    public static HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String getToken(){
        return getRequest().getHeader(Consts.HEADER_AUTH);
    }

}
